from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from random import choice
import datetime
from django.core.cache import cache
from rest_framework.mixins import CreateModelMixin
from rest_framework import viewsets
from product.serializers import ContactSerializer
import json

class VerifyCodeAPIView(APIView):

    def generate_code(self):
        """
        生成四位验证码
        :return:
        """
        seeds = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        random_str = []
        for i in range(4):
            random_str.append(choice(seeds))

        return "".join(random_str)

    def get(self, request):
        verifyCode = self.generate_code()
        verifyCode_key = datetime.date.today().strftime("%Y%m%d") + self.generate_code() # 生成缓存key
        cache.set(verifyCode_key, verifyCode, 3600)
        status_resp = status.HTTP_200_OK
        return Response({'verifyCode' : verifyCode, 'verifyCode_key': verifyCode_key}, status=status_resp)


class ContactViewset(CreateModelMixin,viewsets.GenericViewSet):
    """
    提交联系表单
    """
    serializer_class = ContactSerializer

    def create(self, request, *args, **kwargs):
        # data = json.loads(request.data)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        re_dict = serializer.data

        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()

